﻿Public Class HDDocViewForm

    Private _IntevalType As String = "3"
    Private _IntevalValue As Integer = 1

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        If sender.Text = "取消" Then
            sender.Text = "正在取消..."
            sender.Enabled = False
            bwSearch.CancelAsync()
            Exit Sub
        End If

        If CheckValidate() = False Then
            Exit Sub
        End If

        Me.DataGridView1.DataSource = Nothing
        Me.DataGridView1.Columns.Clear()
        Me.DataGridView2.Rows.Clear()
        Me.DataGridView2.Columns.Clear()

        'Me.DataGridView1.Cursor = Cursors.WaitCursor
        Me.cboRef.Enabled = False
        'Me.btnRefresh.Enabled = False
        Me.btnRefresh.Text = "取消"
        Me.btnPrint.Enabled = False
        Me.dtpFrom.Enabled = False
        Me.dtpTo.Enabled = False
        Me.pnlSearch.Visible = True

        Me.bwSearch.RunWorkerAsync(New Object() {cboRef.SelectedItem})
        'RefreshData()
        'Me.dtpFrom.Enabled = True
        'Me.dtpTo.Enabled = True
        'Me.btnRefresh.Enabled = True
        'Me.DataGridView1.Cursor = Cursors.Default

    End Sub

    Dim tArray As New ArrayList()
    Dim hArray As New ArrayList()
    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Function RefreshData(ByVal cbo_rti As RefTypeItem) As Object()
        Dim strSql As String
        'Dim m_index As Integer
        'Dim cbo_rti As RefTypeItem = CType(cboRef.SelectedItem, RefTypeItem)
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)
        Dim ret() As Object = Nothing
        Dim proIndex As Integer
        'Dim tArray As New ArrayList()
        'Dim hArray As New ArrayList()
        tArray.Clear()
        hArray.Clear()

        strSql = String.Format("select hDate")


        '添加AI列标题
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                Dim columnName As String = "AI" & Trim(apti.PortNo.ToString)

                strSql &= String.Format(",{0}", columnName)

                If apti.PortNo <= 9 Then
                    tArray.Add(columnName)
                Else
                    hArray.Add(columnName)
                End If
            End If
        Next


        'If is_firstrun = True Then '当前冷库没有配置AI
        '    msg.Show("指定冷库尚未配置数据端口")
        'End If

        strSql &= String.Format(" From tbccHDData_{0}_{1} Where hDate>='{2}' and hDate<='{3}' order by hDate", Trim(cbo_rti.ProjectID).Replace("-", "_"), cbo_rti.NetId, UtilityClass.GetDateString(Me.dtpFrom.Value), UtilityClass.GetDateString(Me.dtpTo.Value))

        Dim ds As DataSet = Nothing
        Dim tmpObj As Object

        Try
            ds = SqlHelper.ExecuteDataset(strSql, Nothing)



            '时间间隔数据
            Dim iSeconds As Integer = HIST_SAVE_INTERVAL_TIME

            Select Case _IntevalType 'Me.cboIntevalType.Text.Trim()
                Case "1"
                    iSeconds = _IntevalValue 'CInt(Me.cboSecond.Text)

                Case "2"
                    iSeconds = _IntevalValue * 60 'Me.nudMinute.Value * 60

                Case "3"
                    iSeconds = _IntevalValue * 3600 'Me.nudHour.Value * 3600

                Case Else
                    iSeconds = _IntevalValue * 3600
            End Select

            Dim dtStart As DateTime
            dtStart = AdjustDateTime(Me.dtpFrom.Value)

            proIndex = 0
            Dim dtTmp As DateTime
            For Each r As DataRow In ds.Tables(0).Rows
                If Me.bwSearch.CancellationPending Then Return Nothing '取消查询
                tmpObj = r("hdate")
                dtTmp = IIf(IsDBNull(tmpObj) = False, tmpObj, DateTime.MinValue)
                If dtTmp.Subtract(dtStart).TotalSeconds Mod iSeconds <> 0 Then
                    r.Delete()
                End If
                proIndex += 1
                'Me.bwSearch.ReportProgress((proIndex / ds.Tables(0).Rows.Count) * 100) '报告进度
                ReportProgress((proIndex / ds.Tables(0).Rows.Count) * 100)
            Next

            ds.AcceptChanges()


            If ds.Tables(0).Rows.Count <= 0 Then
                'Me.DataGridView1.Columns.Clear()
                'Me.DataGridView2.Columns.Clear()
                'Me.btnPrint.Enabled = False
                'msg.Show("指定时间范围没有数据,请重新设置时间范围")
                ds.Clear() : ds.Dispose() : ds = Nothing
                Return Nothing
                'Else
                '    Me.btnPrint.Enabled = True
            End If


            '添加DataSet列
            Dim table As DataTable = ds.Tables(0)
            If tArray.Count > 0 Then 'array.count > 0
                table.Columns.Add("hTMax")
                table.Columns.Add("hTMin")
                table.Columns.Add("hTAvg")
            End If
            If hArray.Count > 0 Then 'array.count > 0
                table.Columns.Add("hHMax")
                table.Columns.Add("hHMin")
                table.Columns.Add("hHAvg")
            End If

            ds.AcceptChanges()


            'min/max/avg
            Dim hMin, hMax, hAvg As Double
            Dim hSum As Decimal
            Dim vRow As Integer = 0
            Dim vLen As Integer = tArray.Count + hArray.Count
            'If tArray.Count > 1 Then vLen += 3 '去处统计中T的3列; 2008.10.31
            'If hArray.Count > 1 Then vLen += 3 '去处统计中H的3列; 2008.10.31
            Dim vMin(vLen - 1), vMax(vLen - 1), vAvg(vLen - 1) As Double
            Dim vSum(vLen - 1) As Decimal
            For i As Integer = 0 To vLen - 1
                vMin(i) = Double.MaxValue : vMax(i) = Double.MinValue : vAvg(i) = 0 : vSum(i) = 0
            Next
            For Each r As DataRow In ds.Tables(0).Rows
                If Me.bwSearch.CancellationPending Then Return Nothing '取消查询
                '计算温度水平/垂直min/max/avg值
                If tArray.Count > 0 Then 'array.count > 0
                    hMin = Double.MaxValue : hMax = Double.MinValue : hAvg = 0 : hSum = 0
                    For i As Integer = 0 To tArray.Count - 1
                        tmpObj = r(tArray(i))
                        Dim value As Double
                        If UtilityClass.IsNotNullEmpty(tmpObj) = False Then
                            value = 0
                            r(tArray(i)) = value
                        Else
                            value = tmpObj
                        End If
                        '水平
                        If value < hMin Then hMin = value
                        If value > hMax Then hMax = value
                        hSum += value

                        '垂直
                        If value < vMin(i) Then vMin(i) = value
                        If value > vMax(i) Then vMax(i) = value
                        vSum(i) += value
                    Next
                    hAvg = hSum / tArray.Count
                    r("hTMax") = hMax
                    r("hTMin") = hMin
                    r("hTAvg") = Math.Round(hAvg, 2)
                End If

                '计算湿度水平/垂直min/max/avg值
                If hArray.Count > 0 Then 'array.count > 0
                    hMin = Double.MaxValue : hMax = Double.MinValue : hAvg = 0 : hSum = 0
                    For i As Integer = 0 To hArray.Count - 1
                        tmpObj = r(hArray(i))
                        Dim value As Double
                        If UtilityClass.IsNotNullEmpty(tmpObj) = False Then
                            value = 0
                            r(hArray(i)) = value
                        Else
                            value = tmpObj
                        End If
                        '水平
                        If value < hMin Then hMin = value
                        If value > hMax Then hMax = value
                        hSum += value

                        '垂直
                        Dim j As Integer = tArray.Count + i
                        value = r(j + 1) 'i + 1跳过时间列
                        If value < vMin(j) Then vMin(j) = value
                        If value > vMax(j) Then vMax(j) = value
                        vSum(j) += value
                    Next
                    hAvg = hSum / hArray.Count
                    r("hHMax") = hMax
                    r("hHMin") = hMin
                    r("hHAvg") = Math.Round(hAvg, 2)
                End If

                ''计算温度垂直min/max/avg值
                'If tArray.Count > 0 Then
                '    For i As Integer = 0 To tArray.Count - 1
                '        Dim value As Double = r(tArray(i))
                '        If value < vMin(i) Then vMin(i) = value
                '        If value > vMax(i) Then vMax(i) = value
                '        vSum(i) += value
                '    Next
                'End If

                ''计算湿度垂直min/max/avg值
                'If hArray.Count > 0 Then
                '    For i As Integer = tArray.Count To vLen - 1
                '        Dim value As Double = r(i + 1) 'i + 1跳过时间列
                '        If value < vMin(i) Then vMin(i) = value
                '        If value > vMax(i) Then vMax(i) = value
                '        vSum(i) += value
                '    Next
                'End If

                vRow += 1
                'Me.bwSearch.ReportProgress((vRow / ds.Tables(0).Rows.Count) * 100) '报告进度
                ReportProgress((vRow / ds.Tables(0).Rows.Count) * 100)
            Next
            For i As Integer = 0 To vLen - 1
                vAvg(i) = vSum(i) / vRow
            Next

            'Dim row As DataRow
            'row = table.NewRow()
            'row(0) = "最大值"
            'For i As Integer = 0 To vLen - 1
            '    row(i + 1) = vMax(i)
            'Next
            'table.Rows.Add(row)

            'row = table.NewRow()
            'row(0) = "最小值"
            'For i As Integer = 0 To vLen - 1
            '    row(i + 1) = vMin(i)
            'Next
            'table.Rows.Add(row)

            'row = table.NewRow()
            'row(0) = "平均值"
            'For i As Integer = 0 To vLen - 1
            '    row(i + 1) = Math.Round(vSum(i) / vRow, 4)
            'Next
            'table.Rows.Add(row)

            ds.AcceptChanges()

            ret = New Object() {ds, vMax, vMin, vAvg, vLen}


        Catch ex As Exception
            'Me.DataGridView1.Columns.Clear()
            'Me.DataGridView2.Columns.Clear()
            'Me.btnPrint.Enabled = False
            'msg.Show("指定时间范围没有数据,请重新设置时间范围")
            If ds IsNot Nothing Then
                ds.Clear() : ds.Dispose() : ds = Nothing
            End If
        End Try

        Return ret
    End Function

    ''' <summary>
    ''' 检查时间范围是否合法
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckValidate() As Boolean
        If Me.dtpTo.Value < Me.dtpFrom.Value Then
            msg.ShowWarning("起始时间不能大于终止时间。")
            Me.dtpFrom.Focus()
            Return False
        End If

        '限制查询的历史记录数量
        Dim ratio As Integer = 1
        Select Case _IntevalType
            Case "1"
                ratio = 1
            Case "2"
                ratio = 6

            Case "3"
                ratio = 360
            Case Else
                Return False
        End Select

        If Me.dtpTo.Value > Me.dtpFrom.Value.AddDays(7 * ratio) Then
            msg.ShowWarning(String.Format("查询的时间间隔不能超过{0}天", 7 * ratio))
            Me.dtpFrom.Focus()
            Return False
        End If

        Return True
    End Function

    Private Function AdjustDateTime(ByVal dt As DateTime) As DateTime
        Return dt.AddSeconds(-dt.Second Mod HIST_SAVE_INTERVAL_TIME)
    End Function

    Private Sub HDDocViewForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DataGridView1.AutoGenerateColumns = False

        'Me.cboIntevalType.SelectedIndex = 2
        Me.cboRef.SelectedIndex = -1

        Dim dt As DateTime = UtilityClass.GetDateString(Now)
        dtpTo.Value = dt
        dtpFrom.Value = dt.ToLongDateString()
        'dtpFrom.Value = dtpFrom.Value.AddMonths(-1)
        dtpFrom.Value = dtpFrom.Value.AddDays(-1)
        LoadRef()

    End Sub

    Private Sub LoadRef()
        Dim rts As RefTypeService = New RefTypeService(MainForm.pi)

        For Each rti As RefTypeItem In rts.GeRefGroupList()
            cboRef.Items.Add(rti)
        Next

        '获取时间间隔参数; 2008.10.31
        Dim it, iv As String
        it = KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "DocViewType")
        iv = KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "DocViewValue")
        If it.Length > 0 Then _IntevalType = it
        If iv.Length > 0 Then _IntevalValue = CInt(iv)

        cboRef.SelectedIndex = -1
        btnRefresh.Enabled = False
        btnPrint.Enabled = False
    End Sub

    Dim cols(100) As String
    Dim headers(100) As String

    Private Sub Print()
        Dim dt As DataTable
        dt = CType(Me.DataGridView1.DataSource, DataTable)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If

        Dim objExcel As New Excel.Application

        Dim wb As Excel.Workbook = objExcel.Workbooks.Add()

        '  excel.Application.Workbooks.Add(True)
        'objExcel.Visible = True

        ReDim Preserve cols(100)


        Dim index As Integer = 0
        cols(index) = "序号"
        headers(index) = "序号"
        For i As Integer = 0 To Me.DataGridView1.Columns.Count - 1
            If Me.DataGridView1.Columns(i).Visible Then
                index += 1
                cols(index) = Me.DataGridView1.Columns(i).DataPropertyName
                headers(index) = Me.DataGridView1.Columns(i).HeaderText
            End If
        Next

        ReDim Preserve cols(index)

        'Dim bRow As Integer = dt.Rows.Count
        ''Dim values(,) As Object
        Dim values(dt.Rows.Count, cols.Length + 1) As Object 'cols.Length + 1:时间为2列
        'If bRow Mod 32 <> 0 Then
        '    Dim ba As Integer = bRow \ 32
        '    bRow = (ba + 1) * 32
        '    'ReDim values(bRow, cols.Length)
        'Else
        '    'ReDim values(bRow, cols.Length)
        'End If
        'For i As Integer = 0 To values.GetLength(0) - 1
        '    For j As Integer = 0 To values.GetLength(1) - 1
        '        values(i, j) = Strings.Space(1)
        '    Next
        'Next

        For j As Integer = 0 To cols.Length
            If j > 1 Then
                values(0, j + 1) = headers(j) 'j+1:跳过时间2列(共2列)
            Else
                values(0, j) = headers(j)
            End If
        Next

        '
        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            values(i + 1, 0) = i + 1
            For j As Integer = 1 To cols.Length - 1 '跳过GridView第一列
                If j > 1 Then
                    values(i + 1, j + 1) = r(cols(j)) 'j+1:跳过时间2列(共2列)
                Else
                    values(i + 1, j) = r(cols(j))
                End If
            Next
        Next

        'Get stat values
        Dim statValues(3, Me.DataGridView1.Columns.Count) As Object
        For i As Integer = 0 To statValues.GetLength(0) - 1 'init values
            For j As Integer = 0 To statValues.GetLength(1) - 1
                statValues(i, j) = String.Empty
            Next
        Next
        For i As Integer = 0 To Me.DataGridView2.Rows.Count - 1 '3
            Dim r As DataGridViewRow = Me.DataGridView2.Rows(i)
            For j As Integer = 0 To Me.DataGridView2.Columns.Count - 1
                statValues(i, j) = r.Cells(j).Value
            Next j
        Next i

        Dim pwd As String = System.Guid.NewGuid().ToString()
        Try
            'objExcel.Visible = True
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length)).Value = values
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(bRow, cols.Length)).Value = values

            '设置格式
            objExcel.Columns("A:AA").Select()
            objExcel.Selection.HorizontalAlignment = Excel.Constants.xlCenter
            objExcel.Selection.Font.Size = 10
            objExcel.Selection.ColumnWidth = 10

            '序号
            objExcel.Range("A1", "A" & (dt.Rows.Count + 1)).ColumnWidth = 5
            'objExcel.Range("A1", "A" & (dt.Rows.Count + 1)).RowHeight = 20

            '监控时间
            objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 2)).Insert(Excel.XlInsertShiftDirection.xlShiftToRight) '插入合并列
            objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 3)).ColumnWidth = 8
            objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 3)).NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"

            Dim totalIndex As Integer = 4 + tArray.Count + hArray.Count
            '设置温湿度列宽; 2008.10.31
            objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Rows.Count + 1, totalIndex)).ColumnWidth = 6
            objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Rows.Count + 1, totalIndex)).NumberFormatLocal = "0.00"

            '设置温湿度统计列宽; 2008.10.31
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, 26)).ColumnWidth = 8
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, 26)).NumberFormatLocal = "0.00"
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, totalIndex - 1 + IIf(tArray.Count > 0, 3, 0) + IIf(hArray.Count > 0, 3, 0))).Interior.Color = RGB(255, 221, 221) 'array.count > 0

            'Dim pageRow As Integer = 27 '不包括统计的3行; 2008.10.31
            Dim statRow As Integer = 3
            Dim totalCount As Integer = Math.Ceiling(dt.Rows.Count / 30) * 30 - statRow
            If totalCount < dt.Rows.Count Then
                totalCount += statRow
            End If
            '合并单元格
            Dim range As Excel.Range
            range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3)) '合并日期单元格(dt.Rows.Count); 2008.10.31
            range.Merge(True)
            'For i As Integer = 1 To totalCount + 1
            '    range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3))
            '    range.Merge(True)
            'Next
            '合并统计单元格
            range = objExcel.Range(objExcel.Cells(totalCount + 2, 1), objExcel.Cells(totalCount + 4, 2)) '2008.10.31
            'range = objExcel.Range(objExcel.Cells(bRow - 2, 1), objExcel.Cells(bRow, 2))
            range.Merge()
            range.Value2 = "统计"
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
            range.Font.Size = 20

            'cols.Length + 1:时间为2列
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length + 1)).Value = values

            '添加统计信息
            Dim statRange As Excel.Range
            statRange = objExcel.Range(objExcel.Cells(totalCount + 2, 3), objExcel.Cells(totalCount + 4, cols.Length + 1)) '2008.10.31
            'statRange = objExcel.Range(objExcel.Cells(bRow - 2, 3), objExcel.Cells(bRow, cols.Length + 1))
            statRange.Value2 = statValues
            'statRange.Interior.Color = RGB(221, 221, 221)
            'statRange.Interior.Pattern = 4
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Color = RGB(221, 221, 221)
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Pattern = 4

            '设置边框
            range = objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(totalCount + 4, cols.Length + 1))
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous

            '设置保护
            Try
                objExcel.ActiveSheet.Protect(pwd, _
                            AllowFormattingCells:=False, _
                            AllowFormattingColumns:=False, _
                            AllowFormattingRows:=False, _
                            AllowInsertingColumns:=False, _
                            AllowInsertingRows:=False, _
                            AllowInsertingHyperlinks:=False, _
                            AllowDeletingColumns:=False, _
                            AllowDeletingRows:=False _
                )
            Catch ex As Exception
                objExcel.ActiveSheet.Protect(pwd)
            End Try

            '温湿度值
            Dim ws As Excel.Worksheet = objExcel.ActiveSheet
            With ws.PageSetup
                .LeftHeader = "&G" & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                .CenterHeader = String.Format("&""宋体,加粗""&28 {0}温/湿度查询 ", Me.cboRef.Text)
                .RightHeader = vbCr & vbCr & vbCr & "共&N页 第&P页"
                .LeftFooter = "养护员："
                .CenterFooter = ""
                .RightFooter = "打印日期：&D &T"
                .LeftMargin = objExcel.Application.InchesToPoints(0.6)
                .RightMargin = objExcel.Application.InchesToPoints(0.4)
                .TopMargin = objExcel.Application.InchesToPoints(1.08)
                .BottomMargin = objExcel.Application.InchesToPoints(0.68)
                .HeaderMargin = objExcel.Application.InchesToPoints(0.22)
                .FooterMargin = objExcel.Application.InchesToPoints(0.5)
                .PrintHeadings = False
                .PrintGridlines = True
                '.PrintComments = objExcel.xlPrintNoComments
                ''.PrintQuality = 300
                .CenterHorizontally = False
                .CenterVertically = False
                '.Orientation = objExcel.xlPortrait
                .Draft = False
                '.PaperSize = Excel.XlPaperSize.xlPaperA4
                .Orientation = Excel.XlPageOrientation.xlLandscape '横向打印
                '.FirstPageNumber = objExcel.xlAutomatic
                '.Order = objExcel.xlDownThenOver
                '.BlackAndWhite = False
                .Zoom = 100
                '.PrintErrors = objExcel.xlPrintErrorsDisplayed

                '.PrintArea = "A1:U" & bRow
                .FitToPagesWide = 1
                .FitToPagesTall = 1
                .PrintTitleRows = "$1:$1"

                Try

                    With .LeftHeaderPicture
                        .Filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\ClientLogo.jpg"
                        .Height = 68
                        .Width = 68
                        '.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoFalse
                        .LockAspectRatio = 0
                    End With

                Catch ex As Exception
                    .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                    Debug.WriteLine("页眉图片" & ex.ToString())
                End Try

            End With
            'excel.printpreview()
            'excel.PrintPreview()

            objExcel.Visible = True
            'objExcel.ActiveWindow.View = Excel.XlWindowView.xlPageBreakPreview
            objExcel.ActiveWindow.SelectedSheets.PrintPreview()
            'excel.Workbooks(1).PrintOut()
            'excel.DisplayAlerts = False
            'excel.Quit()
        Catch ex As Exception
            Debug.WriteLine("打印错误" & ex.ToString())
            msg.Show(ex.Message)
        Finally
            Try
                If objExcel.ActiveWindow.View = Excel.XlWindowView.xlNormalView Then '分页预览
                    'objExcel.ActiveSheet.Unprotect(pwd)
                    wb.Close(False, False)
                    objExcel.Workbooks.Close()
                    objExcel.DisplayAlerts = False
                    objExcel.Quit()
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wb)
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel)
                    wb = Nothing
                    objExcel = Nothing
                    GC.Collect()
                End If
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try

        End Try
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Me.Cursor = Cursors.WaitCursor
        sender.Enabled = False
        Print()
        sender.Enabled = True
        Me.Cursor = Cursors.Default
    End Sub


    Private Sub cboSecond_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.btnPrint.Enabled = False
    End Sub

    'Private Sub nudHour_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.btnPrint.Enabled = False
    'End Sub

    'Private Sub nudMinute_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.btnPrint.Enabled = False
    'End Sub

    Private Sub dtpFrom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFrom.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub dtpTo_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpTo.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Dim selectValues As New List(Of DataGridViewCell)
    Private Sub DataGridView2_CellMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView2.CellMouseClick
        If e.RowIndex < 0 Then Return
        If e.ColumnIndex < 1 Then Return 'skip first column

        Dim tmpObj As Object
        Dim value As Double

        value = Me.DataGridView2.Item(e.ColumnIndex, e.RowIndex).Value

        'Me.DataGridView1.MultiSelect = False
        'For Each c As DataGridViewCell In Me.DataGridView1.SelectedCells
        '    c.Selected = False
        'Next
        If selectValues.Count > 0 Then '有上次查询记录

            If selectValues(0).ColumnIndex = e.ColumnIndex And selectValues(0).Value = value Then '是选择的值
                selectValues(0).Selected = True
                selectValues.RemoveAt(0)
            Else
                selectValues.Clear() '清空上次列表, 重新加载新查询记录

                For Each r As DataGridViewRow In Me.DataGridView1.Rows
                    tmpObj = r.Cells(e.ColumnIndex).Value
                    If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
                    If tmpObj = value Then
                        selectValues.Add(r.Cells(e.ColumnIndex))
                    End If
                Next

                If selectValues.Count > 0 Then
                    selectValues(0).Selected = True
                    selectValues.RemoveAt(0)
                End If
            End If

        Else '无上次查询记录, 添加新查询记录

            For Each r As DataGridViewRow In Me.DataGridView1.Rows
                tmpObj = r.Cells(e.ColumnIndex).Value
                If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
                If tmpObj = value Then
                    selectValues.Add(r.Cells(e.ColumnIndex))
                    'r.Cells(e.ColumnIndex).Selected = True
                End If
            Next

            If selectValues.Count > 0 Then
                selectValues(0).Selected = True
                selectValues.RemoveAt(0)
            End If

        End If

    End Sub

    Private Sub DataGridView1_CellMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
        If e.RowIndex < 0 Then Return
        If e.ColumnIndex < 1 Then Return '跳过时间列

        Dim tmpObj As Object = Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value
        If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Return
        Dim value As Double = tmpObj

        Select Case Me.DataGridView1.Columns(e.ColumnIndex).Name
            Case "hTMax", "hTMin", "hTAvg"
                For Each col As String In tArray
                    tmpObj = Me.DataGridView1.Rows(e.RowIndex).Cells(col).Value
                    If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
                    If tmpObj = value Then
                        Me.DataGridView1.Rows(e.RowIndex).Cells(col).Selected = True
                    End If
                Next
            Case "hHMax", "hHMin", "hHAvg"
                For Each col As String In hArray
                    tmpObj = Me.DataGridView1.Rows(e.RowIndex).Cells(col).Value
                    If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
                    If tmpObj = value Then
                        Me.DataGridView1.Rows(e.RowIndex).Cells(col).Selected = True
                    End If
                Next
        End Select
    End Sub

    Private Sub cboRef_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboRef.SelectedIndexChanged
        Me.btnPrint.Enabled = False


        If cboRef.SelectedIndex <> -1 Then
            btnRefresh.Enabled = True
        End If
    End Sub

    Private Sub bwSearch_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwSearch.DoWork
        Dim cbo_rti As RefTypeItem = e.Argument(0)
        Dim ret As Object
        e.Result = New Object() {True, Nothing}

        Dim str As String = String.Format("正在查询{0}历史数据……", cbo_rti)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf SetSearchState), str)
        Else
            SetSearchState(str)
        End If

        ret = RefreshData(cbo_rti)

        If Me.InvokeRequired Then
            e.Result(0) = Me.Invoke(New BoolMethodHandler(AddressOf AddDataToGridView), ret)
        Else
            e.Result(0) = AddDataToGridView(ret)
        End If

        e.Result(1) = bwSearch.CancellationPending
    End Sub

    Private Sub bwSearch_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwSearch.ProgressChanged
        pbSearch.Value = e.ProgressPercentage
    End Sub

    Private Delegate Sub VoidMethodHandler(ByVal obj As Object)
    Private Delegate Function BoolMethodHandler(ByVal obj As Object) As Boolean
    Private Sub bwSearch_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwSearch.RunWorkerCompleted
        Me.pnlSearch.Visible = False

        If e.Result(0) Then
            Me.btnPrint.Enabled = True
        ElseIf Not e.Result(1) Then '过滤取消操作
            'Me.DataGridView1.Columns.Clear()
            'Me.DataGridView2.Columns.Clear()
            Me.btnPrint.Enabled = False
            msg.Show("指定时间范围没有数据,请重新设置时间范围")
        End If

        Me.cboRef.Enabled = True
        Me.dtpFrom.Enabled = True
        Me.dtpTo.Enabled = True
        Me.btnRefresh.Enabled = True
        Me.btnRefresh.Text = "查询"
        'Me.DataGridView1.Cursor = Cursors.Default
        GC.Collect()

        If e.Result(1) Then
            msg.Show("操作已取消")
        End If
    End Sub
    Private Sub SetDataGridViewColumnVisible(ByVal flag As Boolean)
        For i As Integer = 0 To DataGridView1.Columns.Count - 1
            Me.DataGridView1.Columns(i).Visible = flag
        Next
        For i As Integer = 0 To DataGridView2.Columns.Count - 1
            Me.DataGridView2.Columns(i).Visible = flag
        Next
    End Sub
    Private Sub AddDataGridViewColumns(ByVal obj As Object)
        Dim m_index As Integer
        Dim _GridViewColumnVisable As Boolean = True
        Dim apts As AiPortTypeService = New AiPortTypeService(Me.cboRef.SelectedItem)

        m_index = Me.DataGridView2.Columns.Add("vRowHead", String.Empty)
        Me.DataGridView2.Columns(m_index).Width = 50
        Me.DataGridView2.Columns(m_index).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        Me.DataGridView2.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.SystemColors.Control
        Me.DataGridView2.Columns(m_index).Frozen = True
        Me.DataGridView2.Columns(m_index).Visible = _GridViewColumnVisable
        Me.DataGridView2.Rows.Add(3)
        Me.DataGridView2.Rows(0).Cells(0).Value = "最大"
        Me.DataGridView2.Rows(1).Cells(0).Value = "最小"
        Me.DataGridView2.Rows(2).Cells(0).Value = "平均"

        '添加时间列标题
        m_index = Me.DataGridView1.Columns.Add("hDate", "时间")
        Me.DataGridView1.Columns(m_index).DataPropertyName = "hDate"
        Me.DataGridView1.Columns(m_index).Width = 140
        Me.DataGridView1.Columns(m_index).Frozen = True
        Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

        '添加AI列标题
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                Dim columnName As String = "AI" & Trim(apti.PortNo.ToString)

                m_index = Me.DataGridView1.Columns.Add(columnName, apti.PortName)
                Me.DataGridView1.Columns(m_index).DataPropertyName = columnName
                Me.DataGridView1.Columns(m_index).SortMode = DataGridViewColumnSortMode.NotSortable '2008.10.31
                Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable
                m_index = Me.DataGridView2.Columns.Add(columnName, apti.PortName) '添加统计列
                Me.DataGridView2.Columns(m_index).Visible = _GridViewColumnVisable
                'Me.DataGridView2.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            End If
        Next

        '添加温度min/max/avg列标题
        If tArray.Count > 0 Then
            m_index = Me.DataGridView1.Columns.Add("hTMax", "最大温度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hTMax"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hTMin", "最小温度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hTMin"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hTAvg", "平均温度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hTAvg"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            '去处统计中T的3列; 2008.10.31
            'Me.DataGridView2.Columns.Add("hTMax", "Tmax") '添加统计列
            'Me.DataGridView2.Columns.Add("hTMin", "Tmin")
            'Me.DataGridView2.Columns.Add("hTAvg", "Tavg")
        End If

        '添加湿度min/max/avg列标题
        If hArray.Count > 0 Then
            m_index = Me.DataGridView1.Columns.Add("hHMax", "最大湿度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hHMax"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hHMin", "最小湿度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hHMin"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hHAvg", "平均湿度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hHAvg"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            '去处统计中H的3列; 2008.10.31
            'Me.DataGridView2.Columns.Add("hHMax", "Hmax") '添加统计列
            'Me.DataGridView2.Columns.Add("hHMin", "Hmin")
            'Me.DataGridView2.Columns.Add("hHAvg", "Havg")
        End If

    End Sub
    Private Sub DataGridView1BindSource(ByVal obj As Object)
        Dim ret = obj
        Dim ds As DataSet = ret(0)
        Dim vMax = ret(1)
        Dim vMin = ret(2)
        Dim vAvg = ret(3)
        Dim vLen = ret(4)

        '绑定DataSet
        Me.DataGridView1.DataSource = ds.Tables(0)

        '取消统计表排序
        For i As Integer = 0 To Me.DataGridView2.Columns.Count - 1
            Me.DataGridView2.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
        Next

        '添加统计信息
        For i As Integer = 0 To vLen - 1
            Me.DataGridView2.Rows(0).Cells(i + 1).Value = vMax(i) 'i + 1跳过第一列
            Me.DataGridView2.Rows(1).Cells(i + 1).Value = vMin(i)
            Me.DataGridView2.Rows(2).Cells(i + 1).Value = Math.Round(vAvg(i), 2)
        Next
    End Sub
    Private Sub SetSearchState(ByVal obj As Object)
        Me.lblSearchState.Text = obj
    End Sub
    Private Function AddDataToGridView(ByVal obj As Object) As Boolean
        If obj IsNot Nothing Then
            AddDataGridViewColumns(Nothing)
            DataGridView1BindSource(obj)
        Else
            Return False
        End If

        Return True
    End Function
    Private Sub ReportProgress(ByVal value As Integer)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf ReportProgressMethod), value)
        Else
            ReportProgressMethod(value)
        End If
    End Sub
    Private Sub ReportProgressMethod(ByVal obj As Object)
        Me.bwSearch.ReportProgress(obj)
    End Sub

    Private Sub HDDocViewForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        DisposeBackWorker()
    End Sub
    Private Sub DisposeBackWorker()
        If Me.bwSearch IsNot Nothing Then
            Me.bwSearch.CancelAsync()
            Me.bwSearch.Dispose() : Me.bwSearch = Nothing
        End If
        GC.Collect()
    End Sub
End Class

